/**
 * Created by gim on 14-1-31.
 */
var _Mongoskin = require('./template/_mongoskin.js');

/**
 * set the functions to the object method
 * only set the 'objMethods' ,and will skip the 'obj'
 * eg . objFindByName  => obj.findByName
 * @param modelClass
 * @param _mongoskin
 */
function setMethodToFn(modelClass,_mongoskin){
    var methodName;
    for(var k in _mongoskin){
        if ('obj' != k.substring(0, 3)) {
            continue;
        }
        methodName = k.substring(3, 4).toLowerCase() + k.substring(4);
        modelClass.prototype[methodName] = _mongoskin[k];
    }

}

/**
 * model builder
 * the method will add the template functions
 * when you require first time
 *
 * @param modelInfo
 * @returns {instance|*}
 */
function defaultModelBuilder(modelInfo){
    var modelClass = modelInfo.instance;
    if (typeof modelClass == 'object'){
        throw new Error("only support function defined !");
    }
    var template = modelInfo.template;
    if (modelInfo.template == null)
    {
        template = _Mongoskin.createNew(modelInfo.db,modelInfo.collection);
    }
    template.__proto__ = modelClass.__proto__;
    modelClass.__proto__ = template;
    setMethodToFn(modelClass,template);
    return modelClass;
}


module.exports = function(modelInfo){
  return defaultModelBuilder(modelInfo);
};
